import React, { Component } from 'react'
import { Text, StyleSheet, View, Alert, Button } from 'react-native'
import Geolocation from '@react-native-community/geolocation';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Storage from '../AsyncStorage/storage'

export default class index extends Component {
    componentDidMount = () => {
        //组件挂载时，请求当前位置信息
        const locationKey =  Storage.get('locationKey')
        if(locationKey===undefined || locationKey=== ''){
            this.getGeolocation()
        }else{
            const location = locationKey
            Alert.alert('当前位置', `纬度：${location.latitude}，经度：${location.longitude}`)
        }
        
    }

    getGeolocation = () => {
        Geolocation.getCurrentPosition(
            info => {
                console.log(info)
                AsyncStorage.setItem('locationKey', JSON.stringify(info))
            },
            error=> Alert.alert('Error', JSON.stringify(error.message)),
            {
                timeout: 20000
            }
        );
    }
    
  render() {
    return (
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <Button style={[styles.button]} title='清除' onPress={Storage.clear}/>
        <Button style={[styles.button]} title='获取位置' onPress={this.getGeolocation}/>
      </View>
    )
  }
}

const styles = StyleSheet.create({})
